import React, { useEffect, useState } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import mapData from '../../../constants/mpaData.json';
import './index.css';
import markerIcon from 'assets/online.png';


const MonitorView = () => {
  const [map, setMap] = useState(null);
  const [cluster, setCluster] = useState(null);
  const [infoWindow, setInfoWindow ] = useState(null)
  const [lnglat] = useState([106.101458,35.637662])

  useEffect(() => {
    initMap();
  }, []);

  // 监听 map 的变化
  useEffect(() => {
    if (map) {
      console.log('地图初始化成功:', map);
      map.on('click',() =>{
        infoWindow.close()
      })

    }
  }, [map]);

  const initMap = async () => {
    try {
      const AMap = await AMapLoader.load({
        key: '67711654050308be8ba5bb03f912b1e9',  // 更新为你的密钥
        version: '2.0',
        plugins: ['AMap.MarkerClusterer']
      });

      const imageLayer = new AMap.ImageLayer({
        url: 'https://amappc.cn-hangzhou.oss-pub.aliyun-inc.com/lbs/static/img/dongwuyuan.jpg',
        bounds: new AMap.Bounds(
            [116.327911, 39.939229],
            [116.342659, 39.946275]
        ),
        zooms: [15, 20]
    });

      const mapInstance = new AMap.Map('container', {
        zoom: 4,
        center: lnglat,
        viewMode: '3D',
        layers: [
          AMap.createDefaultLayer(),
          imageLayer,
      ]
      });

      setMap(mapInstance);
      const newInfoWindow = new AMap.InfoWindow({
        offset: new AMap.Pixel(0, -30), // 窗体偏移量
      });
      setInfoWindow(newInfoWindow); // 更新状态

  //     //创建右键菜单
  //   let contextMenu = new AMap.ContextMenu();

  //   //右键放大
  //   contextMenu.addItem("放大一级", function () {
  //     mapInstance.zoomIn();
  //   }, 0);

  //   //右键缩小
  //   contextMenu.addItem("缩小一级", function () {
  //     mapInstance.zoomOut();
  //   }, 1);

  //   //右键显示全国范围
  //   contextMenu.addItem("缩放至全国范围", function (e) {
  //     mapInstance.setZoomAndCenter(4, [108.946609, 34.262324]);
  //   }, 2);

   
  //   let contextMenuPositon = ''
  //   //地图绑定鼠标右击事件——弹出右键菜单
  //   mapInstance.on('rightclick', function (e) {
  //       contextMenu.open(map, e.lnglat);
  //       contextMenuPositon = e.lnglat;
  //   });

  //    //右键添加Marker标记
  //    contextMenu.addItem("添加标记", function (e) {
  //     var marker = new AMap.Marker({
  //         map: mapInstance,
  //         position: contextMenuPositon //基点位置
  //     });
  // }, 3);

  //   contextMenu.open(mapInstance, lnglat);

  let contextMenu = new AMap.ContextMenu();
  contextMenu.addItem("放大一级", () => mapInstance.zoomIn(), 0);
  contextMenu.addItem("缩小一级", () => mapInstance.zoomOut(), 1);
  contextMenu.addItem("缩放至全国范围", () => mapInstance.setZoomAndCenter(4, [108.946609, 34.262324]), 2);

  let contextMenuPositon = null;

  // 绑定右键点击事件
  mapInstance.on('rightclick', (e) => {
    contextMenu.open(mapInstance, e.lnglat);  // 使用点击位置
    contextMenuPositon = e.lnglat;  // 更新点击位置
  });

  // 右键菜单添加标记
  contextMenu.addItem("添加标记", (e) => {
    if (contextMenuPositon) {
      const marker = new AMap.Marker({
        map: mapInstance,
        position: contextMenuPositon
      });
    }
  }, 3);

      const markers = mapData.data.filter(item => item.loc)
      .map(_ => {
        const [longitude, latitude] = _.loc.split(',')
        return {
          lnglat: [longitude, latitude],
          id: _.id,
          loc:_.loc,
          lastLoc:_.lastLoc,
          vin: _.vin,
          vehicleNo: _.vehicleNo,
          vechileState: _.vechileState,
          chargeState: _.chargeState,
          mode: _.mode,
          maxLevel: _.maxLevel,
          soc: _.soc
        }
      });

      // 创建聚合对象
      const clusterInstance = new AMap.MarkerClusterer(
        mapInstance,
        markers,
         {
        gridSize: 80,
        // renderClusterMarker: (context) => {
        //   // 自定义聚合点样式
        //   context.marker.setContent(`
        //     <div class="custom-cluster">
        //       <div class="cluster-count">${count}</div>
        //     </div>
        //   `);
        // },
        renderMarker: (context) => {
            const loc = context.data[0].loc.split(',');  // 当前经纬度
            const lastLoc = context.data[0].lastLoc.split(',');  // 上一个经纬度
            // 计算方向角
            const heading = calculateHeading([parseFloat(loc[0]), parseFloat(loc[1])], [parseFloat(lastLoc[0]),parseFloat(lastLoc[1])]);
          // 自定义单个点的样式
          context.marker.setContent(`
          <img src="${markerIcon}" class="marker-icon" style="transform: rotate(${heading}deg); transform-origin: center center;" />
          `);
          // 添加点击事件
          context.marker.on('click', () => {
            showVehicleDetail(context,mapInstance);
          });
          
          context.marker.on('mouseover', () => {
            const info = context.data[0]
            const content = `
            <div style="padding: 10px; font-size: 12px;">
              <h1 style="font-size: 14px;">当前车辆信息:</h1>
              <div><strong>vin</strong>: ${info.vin || '未知'}</div>
              <div><strong>车牌号</strong>: ${info.vehicleNo || '未知'}</div>
              <div><strong>状态</strong>: ${info.maxLevel}</div>
              <div><strong>车辆类型</strong>: ${info.mode || '未知'}</div>
              <div><strong>电量</strong>: ${info.soc + '%' || '未知'}</div>
            </div>
          `;
            newInfoWindow.setContent(content);
            newInfoWindow.open(mapInstance, context.marker.getPosition());
          });

          // 鼠标移出事件
          context.marker.on('mouseout', () => {
            // newInfoWindow.close();
          });
        }
      });
          

      setCluster(clusterInstance);
    } catch (error) {
      console.error('地图加载失败：', error);
    }
  };

  const calculateHeading = (loc1, loc2) => {
    const lat1 = loc1[1] * Math.PI / 180;  // 纬度转为弧度
    const lon1 = loc1[0] * Math.PI / 180;  // 经度转为弧度
    const lat2 = loc2[1] * Math.PI / 180;
    const lon2 = loc2[0] * Math.PI / 180;
  
    const deltaLon = lon2 - lon1;
  
    const y = Math.sin(deltaLon) * Math.cos(lat2);
    const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(deltaLon);
  
    // 计算方向角（以度为单位）
    let angle = Math.atan2(y, x) * 180 / Math.PI;
    if (angle < 0) {
      angle += 360;  // 角度调整到0-360度范围
    }
  
    return angle;
  }
 
  const showVehicleDetail = (vehicleInfo, mapInstance) => {
    const { lat, lng } = vehicleInfo.data[0].lnglat;
    // 使用 panTo 先平滑移动中心点
      mapInstance.panTo([lng, lat]);
      mapInstance.setZoom(15);
    // mapInstance.setCenter([lng, lat]);
    // 延迟一段时间后再平滑缩放
      // mapInstance.setZoomAndCenter(20, [lng, lat], true);
      console.log('当前缩放级别:', mapInstance.getZoom());
  };

  return (
    <div className="monitor-container">
        <div id="container" className="map-container"></div>
    </div>
  );
};

export default MonitorView; 